<template>
  <view>
    <canvas canvas-id="watermarkCanvas"
            :style="{ width: w+'px', height: h+'px' }" class="watermark"></canvas>
  </view>
</template>

<script>
import config from '@/config';
import {getToken} from "@/utils/auth";
import {uploadImg} from "@/api/login";

export default {
  data() {
    return {
      w: 0,
      h: 0,
    };
  },
  methods: {
    async addTextWatermark(options) {
      try {
        const resultPath = await this.addWatermark(options);
        this.w = 0;
        this.h = 0;
        return  this.uploadWatermark(resultPath)
      } catch (error) {
        console.error('添加水印失败:', error);
      }
    },
    /**
     * 为图片添加水印
     * @param {Object} options - 配置项
     * @param {string} options.src - 原图路径
     * @param {string} [options.text] - 文字水印内容
     * @param {string} [options.image] - 图片水印路径
     * @param {number} [options.x=10] - 水印X坐标
     * @param {number} [options.y=10] - 水印Y坐标
     * @param {number} [options.fontSize=20] - 文字大小
     * @param {string} [options.fontColor='#ffffff'] - 文字颜色
     * @param {number} [options.alpha=0.8] - 透明度
     * @returns {Promise<string>} 带水印的图片临时路径
     */
    async addWatermark(options) {
      let {
        src,
        text = '版权所有 © 2025',
        x = 10,
        y = 10,
        fontSize = 20,
        textRatio = 0.02,
        fontColor = '#ffffff',
        alpha = 1
      } = options;

      return new Promise((resolve, reject) => {
        // 获取原图信息
        uni.getImageInfo({
          src,
          success: (imageInfo) => {
            const {width, height} = imageInfo;
            this.w = width;
            this.h = height;

            setTimeout(() => {
              // 创建Canvas上下文
              const ctx = uni.createCanvasContext('watermarkCanvas');

              // 绘制原图
              ctx.drawImage(src, 0, 0, width, height);
              // 设置透明度
              ctx.globalAlpha = alpha;

              // 计算文字大小（根据图片宽度按比例缩放）
              fontSize = Math.floor(width * textRatio);
              // 绘制文字水印
              if (text) {
                ctx.setFontSize(fontSize);
                ctx.setFillStyle(fontColor);
                if (x < 0) {
                  // 统计非字母和数字的字符
                  const otherChars = text.match(/[^a-zA-Z0-9]/g) || [];
                  const length = text.length - otherChars.length
                  x = width + x-(fontSize*(length+2));
                }
                if (y < 0) {
                  y = height + y-fontSize;
                }
                ctx.fillText(text, x+fontSize, y+fontSize);
              }
              // 仅文字水印时直接绘制
              ctx.draw(false, () => this.exportCanvasImage(ctx, resolve, reject));
            }, 300)

          },
          fail: reject
        });
      });
    },

    /**
     * 导出Canvas为图片文件
     */
    exportCanvasImage(ctx, resolve, reject) {
      // 延迟执行，确保Canvas绘制完成
      setTimeout(() => {
        uni.canvasToTempFilePath({
          fileType: 'jpg', // 选择jpeg格式（体积更小）
          quality: 0.5, // 质量参数（0~1，0.7为推荐值）
          canvasId: 'watermarkCanvas',
          success: (res) => resolve(res.tempFilePath),
          fail: (err) => reject(new Error(`导出图片失败: ${err.errMsg}`))
        });
      }, 300);
    },
    uploadWatermark(filePath) {
      return  new Promise((resolve, reject) => {
        uploadImg({ filePath,name: 'file'}).then(res => {
              if (res.code === 0) {
                resolve(res.data.url)
              }else {
                reject(new Error(`上传图片失败: ${res.msg}`))
              }
        });
      })
    },
  }
};
</script>
<style scoped>
.watermark {
  position: absolute;
  top: -9999px;
  left: 0;
  z-index: 9999;
}
</style>
